/*
 * @Author: 
 * @Date: 2025-06-30 10:32:17
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2025-07-03 12:07:20
 * @Description: 检测成果控制器
 */
import { 
  Controller, 
  Get, 
  Post, 
  Put, 
  Del, 
  Body, 
  Param, 
  Query,
  Inject,
  File
} from '@midwayjs/decorator';
import { HttpStatus } from '@midwayjs/core';
import { 
  ApiTags, 
  ApiOperation, 
  ApiResponse, 
  ApiParam,
  ApiQuery,
  ApiBody,
  BodyContentType
} from '@midwayjs/swagger';
import { DetectionResultsService } from '../service/detection-results.service';
import {
  CreateSoilEtDto,
  UpdateSoilEtDto,
  SoilEtQueryDto,
  SoilEtResponseDto,
  PageResponseDto,
  CommonResponseDto,
  CsvContentResponseDto,
  CsvStructureDto,
} from '../dto/detection-results.dto';
import { CreateCsvFileDto, CsvFileResponseDto } from '../service/detection-results.service';

// 上传CSV文件DTO
export class UploadCsvDto {
  originalName?: string;
  remark?: string;
}

@ApiTags('检测成果管理')
@Controller('/api/detection-results')
export class DetectionResultsController {
  
  @Inject()
  detectionResultsService: DetectionResultsService;

  // ============= 土含与蒸散发反演成果相关接口 =============

  @ApiOperation({ summary: '创建土含蒸散发成果' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: '创建成功',
    type: SoilEtResponseDto
  })
  @Post('/soil-et')
  async createSoilEt(@Body() dto: CreateSoilEtDto): Promise<CommonResponseDto<SoilEtResponseDto>> {
    try {
      const result = await this.detectionResultsService.createSoilEt(dto);
      return {
        code: HttpStatus.OK,
        message: '创建成功',
        data: result,
        timestamp: Date.now()
      };
    } catch (error) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: error.message || '创建失败',
        timestamp: Date.now()
      };
    }
  }

  @ApiOperation({ summary: '分页查询土含蒸散发成果' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: '查询成功',
    type: PageResponseDto<SoilEtResponseDto>
  })
  @Get('/soil-et')
  async querySoilEt(@Query() query: SoilEtQueryDto): Promise<CommonResponseDto<PageResponseDto<SoilEtResponseDto>>> {
    try {
      const result = await this.detectionResultsService.querySoilEt(query);
      return {
        code: HttpStatus.OK,
        message: '查询成功',
        data: result,
        timestamp: Date.now()
      };
    } catch (error) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: error.message || '查询失败',
        timestamp: Date.now()
      };
    }
  }

  @ApiOperation({ summary: '根据ID获取土含蒸散发成果' })
  @ApiParam({ name: 'id', description: '成果ID' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: '获取成功',
    type: SoilEtResponseDto
  })
  @Get('/soil-et/:id')
  async getSoilEtById(@Param('id') id: number): Promise<CommonResponseDto<SoilEtResponseDto>> {
    try {
      const result = await this.detectionResultsService.getSoilEtById(id);
      return {
        code: HttpStatus.OK,
        message: '获取成功',
        data: result,
        timestamp: Date.now()
      };
    } catch (error) {
      return {
        code: HttpStatus.NOT_FOUND,
        message: error.message || '数据不存在',
        timestamp: Date.now()
      };
    }
  }

  @ApiOperation({ summary: '更新土含蒸散发成果' })
  @ApiParam({ name: 'id', description: '成果ID' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: '更新成功',
    type: SoilEtResponseDto
  })
  @Put('/soil-et/:id')
  async updateSoilEt(
    @Param('id') id: number,
    @Body() dto: UpdateSoilEtDto
  ): Promise<CommonResponseDto<SoilEtResponseDto>> {
    try {
      const result = await this.detectionResultsService.updateSoilEt(id, dto);
      return {
        code: HttpStatus.OK,
        message: '更新成功',
        data: result,
        timestamp: Date.now()
      };
    } catch (error) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: error.message || '更新失败',
        timestamp: Date.now()
      };
    }
  }

  @ApiOperation({ summary: '删除土含蒸散发成果' })
  @ApiParam({ name: 'id', description: '成果ID' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: '删除成功'
  })
  @Del('/soil-et/:id')
  async deleteSoilEt(@Param('id') id: number): Promise<CommonResponseDto<null>> {
    try {
      await this.detectionResultsService.deleteSoilEt(id);
      return {
        code: HttpStatus.OK,
        message: '删除成功',
        timestamp: Date.now()
      };
    } catch (error) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: error.message || '删除失败',
        timestamp: Date.now()
      };
    }
  }

  @ApiOperation({ summary: '获取所有土含蒸散发成果' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: '获取成功',
    type: [SoilEtResponseDto]
  })
  @Get('/soil-et/all')
  async getAllSoilEt(): Promise<CommonResponseDto<SoilEtResponseDto[]>> {
    try {
      const result = await this.detectionResultsService.getAllSoilEt();
      return {
        code: HttpStatus.OK,
        message: '获取成功',
        data: result,
        timestamp: Date.now()
      };
    } catch (error) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: error.message || '获取失败',
        timestamp: Date.now()
      };
    }
  }

  // ============= CSV文件相关接口 =============

  @Post('/csv/upload', { summary: 'CSV文件上传' })
  @ApiBody({
    description: 'CSV文件上传',
    contentType: BodyContentType.Multipart,
  })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: '上传成功',
    type: CsvFileResponseDto
  })
  async uploadCsv(@Query() params: UploadCsvDto, @File() file: any): Promise<CommonResponseDto<CsvFileResponseDto>> {
    try {
      const dto: CreateCsvFileDto = {
        originalName: params.originalName || file.filename,
        filePath: file.data || file.path,
        fileSize: file.size || 0
      };

      const result = await this.detectionResultsService.createCsvFile(dto);
      return {
        code: HttpStatus.OK,
        message: '上传成功',
        data: result,
        timestamp: Date.now()
      };
    } catch (error) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: error.message || '上传失败',
        timestamp: Date.now()
      };
    }
  }

  @ApiOperation({ summary: '获取所有CSV文件' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: '获取成功',
    type: [CsvFileResponseDto]
  })
  @Get('/csv')
  async getAllCsvFiles(): Promise<CommonResponseDto<CsvFileResponseDto[]>> {
    try {
      const result = await this.detectionResultsService.getAllCsvFiles();
      return {
        code: HttpStatus.OK,
        message: '获取成功',
        data: result,
        timestamp: Date.now()
      };
    } catch (error) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: error.message || '获取失败',
        timestamp: Date.now()
      };
    }
  }

  @ApiOperation({ summary: '根据ID获取CSV文件' })
  @ApiParam({ name: 'id', description: 'CSV文件ID' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: '获取成功',
    type: CsvFileResponseDto
  })
  @Get('/csv/:id')
  async getCsvFileById(@Param('id') id: string): Promise<CommonResponseDto<CsvFileResponseDto>> {
    try {
      const result = await this.detectionResultsService.getCsvFileById(id);
      return {
        code: HttpStatus.OK,
        message: '获取成功',
        data: result,
        timestamp: Date.now()
      };
    } catch (error) {
      return {
        code: HttpStatus.NOT_FOUND,
        message: error.message || '文件不存在',
        timestamp: Date.now()
      };
    }
  }

  @ApiOperation({ summary: '删除CSV文件' })
  @ApiParam({ name: 'id', description: 'CSV文件ID' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: '删除成功'
  })
  @Del('/csv/:id')
  async deleteCsvFile(@Param('id') id: string): Promise<CommonResponseDto<null>> {
    try {
      await this.detectionResultsService.deleteCsvFile(id);
      return {
        code: HttpStatus.OK,
        message: '删除成功',
        timestamp: Date.now()
      };
    } catch (error) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: error.message || '删除失败',
        timestamp: Date.now()
      };
    }
  }

  @ApiOperation({ summary: '根据文件名搜索CSV文件' })
  @ApiQuery({ name: 'name', description: '文件名' })
  @ApiResponse({ 
    status: HttpStatus.OK, 
    description: '搜索成功',
    type: [CsvFileResponseDto]
  })
  @Get('/csv/search')
  async searchCsvFiles(@Query('name') name: string): Promise<CommonResponseDto<CsvFileResponseDto[]>> {
    try {
      const result = await this.detectionResultsService.findCsvFileByName(name);
      return {
        code: HttpStatus.OK,
        message: '搜索成功',
        data: result,
        timestamp: Date.now()
      };
    } catch (error) {
      return {
        code: HttpStatus.INTERNAL_SERVER_ERROR,
        message: error.message || '搜索失败',
        timestamp: Date.now()
      };
    }
  }
 
@ApiOperation({ summary: '读取CSV文件内容' })
@ApiParam({ name: 'id', description: 'CSV文件ID' })
@ApiQuery({ name: 'page', description: '页码', required: false })
@ApiQuery({ name: 'pageSize', description: '每页数量', required: false })
@ApiResponse({ 
  status: HttpStatus.OK, 
  description: '读取成功',
  type: CsvContentResponseDto
})
@Get('/csv/:id/content')
async getCsvContent(
  @Param('id') id: string,
  @Query('page') page: number = 1,
  @Query('pageSize') pageSize: number = 100
): Promise<CommonResponseDto<CsvContentResponseDto>> {
  try {
    const result = await this.detectionResultsService.getCsvContent(id, page, pageSize);
    return {
      code: HttpStatus.OK,
      message: '读取成功',
      data: result,
      timestamp: Date.now()
    };
  } catch (error) {
    return {
      code: HttpStatus.INTERNAL_SERVER_ERROR,
      message: error.message || '读取失败',
      timestamp: Date.now()
    };
  }
}

@ApiOperation({ summary: '获取CSV文件结构信息' })
@ApiParam({ name: 'id', description: 'CSV文件ID' })
@ApiResponse({ 
  status: HttpStatus.OK, 
  description: '获取成功',
  type: CsvStructureDto
})
@Get('/csv/:id/structure')
async getCsvStructure(@Param('id') id: string): Promise<CommonResponseDto<CsvStructureDto>> {
  try {
    const result = await this.detectionResultsService.getCsvStructure(id);
    return {
      code: HttpStatus.OK,
      message: '获取成功',
      data: result,
      timestamp: Date.now()
    };
  } catch (error) {
    return {
      code: HttpStatus.INTERNAL_SERVER_ERROR,
      message: error.message || '获取失败',
      timestamp: Date.now()
    };
  }
}
}